﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace Up2Link.Util
{
    /// <summary>
    /// 提供MD5加密与验证的静态类
    /// </summary>
    public static class CMD5Hash
    {
        /// <summary>
        /// C#提供的MD5类
        /// </summary>
        private static MD5 md5 = MD5.Create();

        /// <summary>
        /// 用于构造MD5码的每一位字符
        /// </summary>
        private static StringBuilder sb;

        /// <summary>
        /// 返回字符串参数的MD5码
        /// </summary>
        /// <param name="input">需要转成MD5码的字符串</param>
        /// <returns>字符串的MD5码</returns>
        public static String GetMD5Hash(String input)
        {
            //将字符串参数以UTF32编码转化为字节数组后，计算MD5码，得到MD5码字节数组
            Byte[] data = md5.ComputeHash(Encoding.UTF32.GetBytes(input));
            sb = new StringBuilder();

            //将数组的每个字节元素转化成十六进制数，获得MD5码
            for (Int32 i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 验证指定input的MD5码是否与指定的MD5码相同
        /// </summary>
        /// <param name="input">输入字符串的MD5码</param>
        /// <param name="hash">用于验证的MD5码</param>
        /// <returns>如果两者相同则返回true，否则返回false</returns>
        public static Boolean VerifyMD5Hash(String input, String hash)
        {
            //返回比较结果，比较时忽略字母大小写
            return hash.Equals(input, StringComparison.OrdinalIgnoreCase);
        }
    }
}
